#coding=utf-8
from stutils import *
set_django_environ()
from stdj.stock.models import *
import random,pickle,threading,time
STRADIR = '/home/jay/ststrategy'

def get_ed(exdate):
    
    eds = Exday.objects.filter(date=exdate)
    n = eds.count()
    if n == 0:return None
    i = random.randint(0, n-1)
    
    return eds[i]

def get_ed2(exdate):
    
    from django.db import connection
    c = connection.cursor()
    c.execute( 'select id from stock_exday where date=%s', (exdate,) )
    
    r = c.fetchall()
    if not r:return None
    ids = [i[0] for i in r]
    id = random.choice(ids)
    
    return Exday.objects.get(pk=id)

def path2str(path):
    keys = path.keys()
    
    r = []
    for k in keys:
        s1 ='('+ k + ',' + path[k] + ')'
        r.append(s1)
        
    return '-->'.join(r)
  
def simulate_once(nday, start, end, verbose=False, log=None):
    
    profit = 1
    path = {}
    
    cur = start 
    while cur < end:
        
        next = None
        
        while True:
            e = get_ed2(cur)
            next = e.afternday(nday)
            if next:break
            
        path[cur] = e.share.code
        
        cur_end = e.price.end
        next_end = next.price.end
        profit = profit * float(next_end / cur_end) - profit*0.01
        
        #
        if verbose:print cur,e.share,profit
        
        cur = next.date.isoformat()
        
    #fn = '/home/jay/p1.db'
    #pickle.dump(path, open(fn, 'w'))
    if log:
        log.write(str(profit))
        log.write('\n')
        log.write(path2str(path))
        log.write('\n')
        #log.flush()
    
    return profit

class RintoutThread(threading.Thread):
    def __init__(self, id, n, nday, start, end):
        threading.Thread.__init__(self)
        
        self.id = id
        self.n = n
        
        self.nday = nday
        self.start_date = start
        self.end_date = end
        
        fn = STRADIR + '/%i.csv'%id 
        self.f = open(fn, 'a')
        
    def run(self):
        print  "线程%i启动."%self.id
        
        for i in range(self.n):
            simulate_once(self.nday, self.start_date, self.end_date, log=self.f)
            if i%50 == 1:self.f.flush()
            
        self.f.close()
        print  "线程%i结束."%self.id
            
if __name__=='__main__':
    '''
    s = time.time()
    eds = ['2007-01-04', '2007-11-06', '2007-10-08', '2007-09-10', '2007-8-13']
    for i in range(100):
        e = random.choice(eds)
        get_ed(e)
   
    f = open('/home/jay/t.txt','a')
    print simulate_once(10, '2007-01-04', '2008-01-01',log=f) 
    t = time.time()
    print t-s
    '''
    
    thread_num = 4
    
    for i in range(1,thread_num+1):
        RintoutThread(i, 1000, 10, '2007-01-04', '2008-01-01').start()
        